package com.javafxboot.util;

import com.itextpdf.text.Image;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.PdfWriter;
import com.javafxboot.entity.PrintUrl;
import com.spire.pdf.PdfDocument;
import com.spire.pdf.PdfPageBase;
import com.spire.pdf.actions.PdfGoToAction;
import com.spire.pdf.general.PdfDestination;
import com.spire.pdf.general.PdfDestinationMode;
import com.spire.pdf.graphics.PdfMargins;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.printing.PDFPageable;
import org.apache.pdfbox.printing.PDFPrintable;
import org.apache.pdfbox.printing.Scaling;
import org.apache.pdfbox.rendering.PDFRenderer;
import org.apache.pdfbox.text.PDFTextStripper;
import org.icepdf.core.exceptions.PDFException;
import org.icepdf.core.pobjects.Document;
import org.icepdf.core.pobjects.Page;
import org.icepdf.core.util.GraphicsRenderingHints;

import javax.imageio.ImageIO;
import javax.net.ssl.HttpsURLConnection;
import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.print.attribute.PrintRequestAttributeSet;
import javax.print.attribute.Size2DSyntax;
import javax.print.attribute.standard.Chromaticity;
import javax.print.attribute.standard.MediaSize;
import javax.print.attribute.standard.MediaSizeName;
import java.awt.*;
import java.awt.geom.Dimension2D;
import java.awt.geom.Point2D;
import java.awt.image.BufferedImage;
import java.awt.image.RenderedImage;
import java.awt.print.*;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;

public class Ok {
    /**
     * 传入一个.pdf 地址
     * @param data 地址
     * @throws Exception
     */
    public static void readPdf(PrintUrl data) throws Exception {
        // 是否排序
        boolean sort = false;
        // 编码方式
        String encoding = "UTF-8";
        // 开始提取页数
        int startPage = 1;
        // 内存中存储的PDF Document
        PDDocument pdDocument = null;
        //输入流
        InputStream inputStream = null;
        PrintWriter out = null;
        BufferedReader in = null;
//        try {
//            try {
                // 当作一个URL来装载文件
                URL url = new URL(data.getUrl());
                HttpURLConnection httpUrlConn = (HttpURLConnection) url.openConnection();
                httpUrlConn.setDoInput(true);
                httpUrlConn.setRequestMethod("GET");

                boolean addHttps = url.toString().startsWith("https");
                if (addHttps) {
                    SSL addSSL = new SSL();
                    addSSL.trustAllHosts((HttpsURLConnection) httpUrlConn);
                    ((HttpsURLConnection) httpUrlConn).setHostnameVerifier(addSSL.DO_NOT_VERIFY);
                    httpUrlConn.connect();
                } else {
                    httpUrlConn.connect();
                }
                inputStream = httpUrlConn.getInputStream();
                pdDocument = PDDocument.load(inputStream);
//            } catch (MalformedURLException e) {
//                System.out.println(e);
//            }
            // 获取页码
            int endPage = pdDocument.getNumberOfPages();
            PDFTextStripper stripper = null;
            stripper = new PDFTextStripper();
            // 设置是否排序
            stripper.setSortByPosition(sort);
            // 设置起始页
            stripper.setStartPage(startPage);
            // 设置结束页
            stripper.setEndPage(endPage);
            //System.out.println(stripper.getText(pdDocument));
            System.out.println(" 输出成功！");

//            try {
                PDFRenderer renderer = new PDFRenderer(pdDocument);
                int pages = pdDocument.getDocumentCatalog().getPages().getCount();
                StringBuffer imgFilePath = null;

                String imgFilePathPrefix = "";
                imgFilePath = new StringBuffer();
                imgFilePath.append(imgFilePathPrefix);
                Date dNow = new Date( );
                SimpleDateFormat ft = new SimpleDateFormat ("yyyy\\MM\\dd\\");
                imgFilePath.append(ft.format(dNow));
                imgFilePath.append(data.getOrderSn()+"-x.pdf");
                File dstFile = new File(imgFilePath.toString());
                //目录不存在则创建
                isexitsPath(""+ft.format(dNow)+"\\pdf");
                pdDocument.save(dstFile);
                String path = print2(dstFile.getPath(), data);
                String pdfPath = pdfToJpg(path, data);
                if(data.getIsPrint()){
                    defaultPrintPDF(pdfPath);
                }
//            } catch (IOException e) {
//                e.printStackTrace();
//            }

//        } finally {
//            if (inputStream != null) {
//                // 关闭输出流
//                inputStream.close();
//            }
//            if (pdDocument != null) {
//                // 关闭PDF Document
//                pdDocument.close();
//            }
//        }
    }

    public static String pdfToJpg(String filePath, PrintUrl data) throws Exception{
        Document document = new Document();

//        try {
            document.setFile(filePath);
            Date dNow = new Date( );
            SimpleDateFormat ft = new SimpleDateFormat ("yyyy\\MM\\dd\\");

            float scale = 5f;// 缩放比例（大图）
            // float scale = 0.2f;// 缩放比例（小图）
            float rotation = 0f;// 旋转角度
            for (int i = 0; i < document.getNumberOfPages(); i++) {
                BufferedImage image = (BufferedImage) document.getPageImage(i,
                        GraphicsRenderingHints.SCREEN,
                        Page.BOUNDARY_CROPBOX,
                        rotation, scale);
                RenderedImage rendImage = image;
//                try {
                    File file = new File(ft.format(dNow)+"onlinePDF_OK.jpg");
                    // 这里png作用是：格式是jpg但有png清晰度
                    ImageIO.write(rendImage, "png", file);
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
                image.flush();
            }
            document.dispose();
            convert(ft.format(dNow)+"onlinePDF_OK.jpg", ft.format(dNow)+data.getOrderSn()+".pdf");
            return ft.format(dNow)+data.getOrderSn()+".pdf";
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
    }

    public static void convert(String source, String target) throws Exception {
        com.itextpdf.text.Document document = new com.itextpdf.text.Document();
        //设置文档页边距
        document.setMargins(0,0,0,0);
        FileOutputStream fos = null;
//        try {
            fos = new FileOutputStream(target);
            PdfWriter.getInstance(document, fos);
            //打开文档
            document.open();
            //获取图片的宽高
            Image image = Image.getInstance(source);
            float imageHeight=image.getScaledHeight();
            float imageWidth=image.getScaledWidth();
            //设置页面宽高与图片一致
            Rectangle rectangle = new Rectangle(imageWidth, imageHeight);
            document.setPageSize(rectangle);
            //图片居中
            image.setAlignment(Image.ALIGN_CENTER);
            //新建一页添加图片
            document.newPage();
            document.add(image);
//        } catch (Exception ioe) {
//            System.out.println(ioe.getMessage());
//        } finally {
//            //关闭文档
            document.close();
//            try {
                fos.flush();
                fos.close();
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//        }
    }

    public static boolean isexitsPath(String path)throws InterruptedException{
        String [] paths=path.split("\\\\");
        StringBuffer fullPath=new StringBuffer();
        for (int i = 0; i < paths.length; i++) {
            fullPath.append(paths[i]).append("\\\\");
            File file=new File(fullPath.toString());
            if(paths.length-1!=i){//判断path到文件名时，无须继续创建文件夹！
                if(!file.exists()){
                    file.mkdir();
                    System.out.println("创建目录为："+fullPath.toString());
                }
            }
        }
        File file=new File(fullPath.toString());//目录全路径
        if (!file.exists()) {
            return true;
        }else{
            return false;
        }
    }

    public static void defaultPrintPDF(String pdfPath) throws IOException, PrinterException {

        File file = new File(pdfPath);
        // 读取pdf文件
        PDDocument document = PDDocument.load(file);
        // 创建打印任务
        PrinterJob job = PrinterJob.getPrinterJob();

        job.setPageable(new PDFPageable(document));

        Paper paper = new Paper();
        // 设置打印纸张大小
        paper.setSize(283,425); // 1/72 inch
        // 设置打印位置 坐标
        paper.setImageableArea(-20, -33, paper.getWidth()+20, paper.getHeight()+10); // no margins
        // custom page format
        PageFormat pageFormat = new PageFormat();
        pageFormat.setPaper(paper);
        // override the page format
        Book book = new Book();
        // append all pages 设置一些属性 是否缩放 打印张数等
        book.append(new PDFPrintable(document, Scaling.SCALE_TO_FIT), pageFormat, 1);
        job.setPageable(book);
        // 开始打印
        job.print();

    }

    public static String print2(String file, PrintUrl data)
    {
        //创建PdfDocument实例
        PdfDocument originalDoc = new PdfDocument();
        //加载PDF文件
        originalDoc.loadFromFile(file);
        //创建一个新的PdfDocument实例
        PdfDocument newDoc = new PdfDocument();
        //遍历所有PDF 页面
        Dimension2D dimension2D = new Dimension();
        for (int i = 0; i < originalDoc.getPages().getCount(); i++) {
            PdfPageBase page = originalDoc.getPages().get(i);
            float scale = 0.48f;
            //设置新文档第一页的页面宽高为原来的1.2倍
            float width = (float) page.getSize().getWidth() * scale;
            float height = (float) page.getSize().getHeight() * scale;
            dimension2D.setSize(width, height);
            //设置新文档第一页的页边距为左右50，上下100
            PdfMargins margins = new PdfMargins(0, 0);
            PdfPageBase newPage = newDoc.getPages().add(dimension2D, margins);
            //复制原文档的内容到新文档
            newPage.getCanvas().drawTemplate(page.createTemplate(), new Point2D.Float());
        }
        //保存PDF
        String reuntnFilePath = file;
        newDoc.saveToFile(reuntnFilePath);
        return reuntnFilePath;
    }

}
